import { getAllServiceWidgets, getWidgetOrField } from '@/utils/util'
import { getServiceData } from '@/api/thing'

export default {
  methods: {
    mixinInitService() {
      //组件相关服务
      const { widgetList, formConfig } = this.formJsonObj
      const allServiceWidgets = getAllServiceWidgets(widgetList)

      const allService = formConfig.services.filter((service) => {
        return allServiceWidgets.some((widget) => widget.options.service.key === service.key)
      })
      const requests = allService.map((service) => {
        //appCode, thingCode, serviceName, method, data, type
        return getServiceData({
          thingCode: service.thingInfo.thingCode,
          serviceName: service.thingInfo.serviceName,
          method: service.method,
          type: service.type,
        })
      })
      /*
      Promise.allSettled(requests).then(reses => {
        reses.map((res, index) => {
          if (res.status === 'fulfilled') {
            const {result} = res.value.data
            setServiceResponseToWidget(this.widgetRefList[allServiceWidgets[index].id], result)
          }
        })
      })
*/
    },
  },
}

/**
 * 将服务响应数据设置到组件中
 * @param widgetRef
 * @param result
 */
function setServiceResponseToWidget(widgetRef, result) {
  const wf = getWidgetOrField(widgetRef)
  switch (wf.type) {
    case 'data-table': {
      /*if (wf.options.service.useModel) {
        widgetRef.setColumns(getColumnsFromDataModel(result));
      }*/
      widgetRef.setTableData(result.rows)
    }
  }
}

function getColumnsFromDataModel(result) {
  //{
  //           columnId: 11,
  //           prop: 'f7',
  //           label: '成功率',
  //           width: '140',
  //           show: true,
  //           align: 'right',
  //           sortable: true,
  //           formatS: 'n7'
  //         },
  const columns = []
  Object.keys(result.dataModel.fieldDefinitions).map((key) => {
    const field = result.dataModel.fieldDefinitions[key]
    columns.push({
      columnId: field.name,
      prop: field.name,
      label: field.description,
    })
  })
  return columns
}
